package com.ycz.springcloud.controller;/*
 @author ycz
 @date 2021-08-19-15:28  
*/

import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.ycz.springcloud.common.Result;
import com.ycz.springcloud.common.validator.ValidatorUtil;
import com.ycz.springcloud.form.SysUserForm;
import com.ycz.springcloud.form.SysUserResetPwdForm;
import com.ycz.springcloud.query.SysUserQuery;
import com.ycz.springcloud.vo.SysUserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@RestController
@RequestMapping("/consumer/sysuser")
public class SysUserController {

    @Autowired
    private RestTemplate restTemplate;
    /**
     * REST_URL 的地址
     */
    private static final String REST_URL="http://CAR-PROVIDER-8001";

    /**
     * 搜索，换页，传list
     * @param query 搜索的query
     * @param page 第几页
     * @param limit 每页的条数
     * @return
     */
    @GetMapping("/page.do")
    public Map<String,Object> page(SysUserQuery query,Integer page,Integer limit){
        System.out.println("发起了搜索请求和换页请求");
//        Map<String,Object> map=restTemplate.postForObject(REST_URL+"/sysuser/page1.do?sex={sex}&" +
//                        "realname={realname}&" +
//                        "phone={phoone}&" +
//                        "IdCard={idCard}&" +
//                        "address={address}&" +
//                        "loginName={loginName}" +
//                        "&page={page}&limit={limit}",null,
//                Map.class,query.getSex(),query.getRealname(),
//                query.getPhone(),query.getIdCard(),query.getAddress(),
//                query.getLoginName(),(page-1)*10,limit);
        query.setPage((page-1)*10);
        query.setLimit(limit);
        System.out.println("page+"+query.getPage()+"limit"+query.getLimit());
       ResponseEntity<Map> mapResponseEntity= restTemplate.postForEntity(REST_URL+"/sysuser/page1.do",query,Map.class);
        System.out.println(mapResponseEntity.getBody());
        List<SysUserVo> sysUserVos= (List<SysUserVo>) mapResponseEntity.getBody().get("data");
      //  List pageList= PageUtil.startPage(sysUserVos,page,limit);
        // 传过来的count，数据库查询到的条数
        Integer total= (Integer) mapResponseEntity.getBody().get("count");
        Map<String, Object> map2 = new HashMap<>();
        map2.put("code",200);
        map2.put("msg","操作成功");
        map2.put("list",sysUserVos);
        map2.put("total",total);
        return map2;
    }


    /**
     * 登录
     * @param loginName 用户名
     * @param loginPassword 密码
     * @param session 设置session
     * @return
     */
    @RequestMapping("/login.do")
    public Object login(String loginName, String loginPassword,HttpSession session){
        System.out.println(loginName+loginPassword);
        Map<String,Object> map= restTemplate.postForObject(REST_URL+
                        "/sysuser/login.do?loginName={loginName}&loginPassword={loginPassword}",
                null,Map.class,
                loginName,
                loginPassword);
        System.out.println(map);
        session.setAttribute("loginName",map.get("loginName"));
        session.setAttribute("role",map.get("role"));
        Result result=new Result();
        result.setCode((Integer) map.get("code"));
        result.setMsg((String) map.get("msg"));
        return result;
    }

    /**
     * 添加记录
     * @param form
     * @return
     */
    @RequestMapping("/add.do")
    public Object add(SysUserForm form){
        System.out.println(form);
        ValidatorUtil.validator(form);//数据校验

        ResponseEntity<Result> result= restTemplate.postForEntity(REST_URL+"/sysuser/add.do",form,
                Result.class);

        return result.getBody();
    }
    /**
     * 导出user的数据
     */
    @RequestMapping("/export.do")
    public void exportUser(SysUserQuery query, HttpServletResponse response) throws IOException {
        System.out.println(query);
//        List<SysUserVo> sysUserVos =  restTemplate.getForObject(REST_URL+"/sysuser/export2.do?sex={sex}&" +
//                        "realname={realname}&" +
//                        "phone={phoone}&" +
//                        "IdCard={idCard}&" +
//                        "address={address}&" +
//                        "loginName={loginName}",List.class,query.getSex(),query.getRealname(),
//                query.getPhone(),query.getIdCard(),query.getAddress(),
//                query.getLoginName());
        /**
         * 代替上面的
         */
        ResponseEntity<List> responseEntity= restTemplate.postForEntity(REST_URL+"/sysuser/export2.do",
                query,List.class);

        System.out.println(responseEntity.getBody());

        //与客户端相关的输出流
        ServletOutputStream os=response.getOutputStream();
        //response为HttpServletResponse对象
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        //test.xls是弹出下载对话框的文件名，不能为中文，中文请自行编码
        String fileName= URLEncoder.encode("客户信息.xls","utf-8");
        response.setHeader("Content-Disposition","attachment;filename="+fileName);
        //符合条件的客户
        System.out.println(responseEntity);
        //将客户转化为excel数据流
        // 通过工具类创建writer，默认创建xls格式
        ExcelWriter writer = ExcelUtil.getWriter();
        //取别名
        writer.addHeaderAlias("id","编号");
        writer.addHeaderAlias("loginName","用户名");
        writer.addHeaderAlias("realname","姓名");
        writer.addHeaderAlias("phone","手机号码");
        writer.addHeaderAlias("idCard","身份证");
        writer.addHeaderAlias("sex","性别");
        writer.addHeaderAlias("address","地址");
        writer.addHeaderAlias("createTime","创建时间");
        writer.addHeaderAlias("img","照片");
        // 一次性写出内容，使用默认样式，强制输出标题
        writer.write(responseEntity.getBody(),true);
        //将Excel输出给浏览器
        writer.flush(os,true);
        System.out.println("  //将Excel输出给浏览器");

    }

    @RequestMapping("/import.do")
    public Result import2(@RequestParam("sysusers")MultipartFile file) throws IOException {
        System.out.println("//解析excel文件");
        ExcelReader render= ExcelUtil.getReader(file.getInputStream());
        System.out.println(render);
        List<SysUserVo> sysUserVos=render.readAll(SysUserVo.class);
        System.out.println(sysUserVos);
//        Map<Integer,SysUserVo> maps=new HashMap<>();
//        for (SysUserVo sysUserVo:sysUserVos){
//            maps.put(sysUserVo.getId(),sysUserVo);
//        }
//        System.out.println(maps);
        Result result = restTemplate.postForObject(REST_URL+"/sysuser/import.do",sysUserVos,Result.class);
        return result;
    }

    @RequestMapping("/delete.do")
    public Result delete(String array){
        System.out.println(array);
        String sub=array.replace("[","");
        String sub1=sub.replace("]","");
        String[] arr=sub1.split(",",'1');
        System.out.println("切割后的长度"+arr.length);

        List<Integer> ids=new ArrayList<>();

        for (String s : arr) {
            Integer id=Integer.parseInt(s);
            ids.add(id);
        }

        Result result=restTemplate.postForObject(
                REST_URL+"/sysuser/delete.do",ids,Result.class
        );
        return result;

    }

    @RequestMapping("/resetPassword.do")
    public Result resetPassword(SysUserResetPwdForm form){
        System.out.println(form);
        ResponseEntity<Result> result=restTemplate.postForEntity(REST_URL+"/sysuser/updatePassword.do",form,Result.class);
        return result.getBody();
    }


}
